package com.entrogy.controller;

import com.entrogy.bean.MachineEntity;
import com.entrogy.bean.Msg;
import com.entrogy.bean.SchoolThdidUrlEntity;
import com.entrogy.service.MachineService;
import com.entrogy.service.SchoolService;
import com.entrogy.service.UserService;
import com.entrogy.utils.ApiReturnUtil;
import com.entrogy.utils.StrUtils;
import com.entrogy.utils.THDio;
import com.entrogy.utils.constants.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author xlr
 * @date 2019.3
 */
@Api(description = "设备管理的操作接口")
@RestController
@RequestMapping(value = "/machinecontroller")
public class MachineController {

	@Autowired
	private THDio thDio;

	@Autowired
	private MachineService machineService;

	@Autowired
	private SchoolService schoolService;

	@ApiOperation(value = "获取我们数据库的全部设备信息")
	@RequestMapping(value = "/getmachinelist",method = RequestMethod.GET)
//	@RequiresPermissions("device:list")
	public Map<String,Object> getMachineList(){
		List<MachineEntity> lists = machineService.listMachine(new MachineEntity());
		return ApiReturnUtil.success("获取所有设备列表成功",lists);
	}

	@ApiOperation(value = "获取实义德的全部设备信息列表")
	@RequestMapping(value = "/getmachinelistthdio",method = RequestMethod.GET)
//	@RequiresPermissions("device:list")
	public net.sf.json.JSONObject getMachineListTHDio(){
		Integer schoolCode = (Integer) SecurityUtils.getSubject().getSession().getAttribute("schoolCode");
		//获取实义德后台地址
		SchoolThdidUrlEntity schoolThididUrl = schoolService.getSchoolThdidUrlAndGroupInfo(schoolCode, Constants.THDID_AI06);
		return thDio.THD_interface(schoolThididUrl.getPathUrl(),"/device/list",new JSONObject(),true, schoolThididUrl.getAccessToken());
	}

	@ApiOperation(value = "根据设备ID获取该设备的详细信息")
	@ApiImplicitParams({
			@ApiImplicitParam(value = "设备ID",name = "device_id",paramType = "query",dataType = "int",required = true)
	})
	@RequestMapping(value = "/getmachinebyid",method = RequestMethod.GET)
//	@RequiresPermissions("device:list")
	public JSONObject getMachineByID(int device_id){
		JSONObject params = new JSONObject();
//		params.put("device_id",device_id);
//		String pathUrl = (String) SecurityUtils.getSubject().getSession().getAttribute("pathUrl");
//		return thDio.THD_interface(pathUrl,"/device/info",params,true);
		return null;
	}

	@ApiOperation(value = "根据设备ID更改其对应设备的信息")
	@ApiImplicitParams({
			@ApiImplicitParam(value = "设备ID",paramType = "query",dataType = "int",required = true,name = "device_id"),
			@ApiImplicitParam(value = "设备名称",paramType = "query",dataType = "String",required = true,name = "device_name"),
			@ApiImplicitParam(value = "成功开闸后的提示信息",paramType = "query",dataType = "String",required = true,name = "appWelcomeMsg"),
			@ApiImplicitParam(value = "识别失败后的提示信息",paramType = "query",dataType = "String",required = true,name = "appFailMsg")
	})
	@RequestMapping(value = "/updatemachineinfo",method = RequestMethod.POST)
//	@RequiresPermissions("device:update")
	public JSONObject updateMachineInfo(int device_id,String device_name,String appWelcomeMsg,String appFailMsg){
//		JSONObject jsonObject = new JSONObject();
//		jsonObject.put("device_id",device_id);
//		JSONObject jsonObject1 = new JSONObject();
//		jsonObject1.put("device_name",device_name);
//		jsonObject1.put("appWelcomeMsg",appWelcomeMsg);
//		jsonObject1.put("appFailMsg",appFailMsg);
//		jsonObject.put("config",jsonObject1.toString());
//		String pathUrl = (String) SecurityUtils.getSubject().getSession().getAttribute("pathUrl");
//		return thDio.THD_interface(pathUrl, "/device/change_func_conf",jsonObject,true);
		return null;
	}

	@ApiOperation(value = "获取实义德某个分组的设备信息列表")
	@RequestMapping(value = "/getGroupMachineList",method = RequestMethod.GET)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "groupId",paramType = "query",dataType = "int",required = true,value = "分组id"),
			@ApiImplicitParam(name = "currentPage",paramType = "query",dataType = "int",required = true,value = "当前页"),
			@ApiImplicitParam(name = "pageSize",paramType = "query",dataType = "int",required = true,value = "每页显示条数"),
			@ApiImplicitParam(name = "keyword",paramType = "query",dataType = "String",required = false,value = "搜索的关键字"),
	})
	public net.sf.json.JSONObject getGroupMachineList(Integer groupId, Integer currentPage, Integer pageSize, String keyword){
//		JSONObject jsonObject = new JSONObject();
//		jsonObject.put("group_id", groupId);
//		jsonObject.put("page", currentPage);
//		jsonObject.put("amount", pageSize);
//		if (StrUtils.isNullOrEmpty(keyword)){
//			jsonObject.put("keyword", keyword);
//		}
//		String pathUrl = (String) SecurityUtils.getSubject().getSession().getAttribute("pathUrl");
//		return thDio.THD_interface(pathUrl, "/device/sublist",jsonObject,true);
		return null;
	}

	@ApiOperation(value = "获取实义德设备分组列表")
	@RequestMapping(value = "/list-thdid-group", method = RequestMethod.GET)
	public net.sf.json.JSONObject listThdidGroup(){
		return thDio.THD_interface("http://62.234.146.219:8088", "/device/list", new net.sf.json.JSONObject(), true, "");
	}

	@ApiOperation(value = "获取学校的实义德的设备列表")
	@RequestMapping(value = "/getSchoolThdidMachineList",method = RequestMethod.GET)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "uid", paramType = "query", dataType = "String", value = "用户id"),
			@ApiImplicitParam(name = "schoolCode", paramType = "query", dataType = "Integer", value = "用户id"),
	})
	public Msg getSchoolThdidMachineList(String uid, Integer schoolCode){
		//学校拥有多种类型的设备，需要调用不同的接口查询设备 // TODO 暂时只有实义德的人脸识别平板以及动态识别摄像头
		//首先获取所有实义德的设备列表
		SchoolThdidUrlEntity schoolThididUrl = schoolService.getSchoolThdidUrlAndGroupInfo(schoolCode, Constants.THDID_AI06);
		JSONObject params = new JSONObject();
		params.put("group_id", 1);
		params.put("page", 1);
		params.put("amount", 100);
		JSONObject jsonObject = thDio.THD_interface(schoolThididUrl.getPathUrl(),"/device/list", params, true, schoolThididUrl.getAccessToken());
		JSONObject jsonObject1 = jsonObject.getJSONObject("data");
		JSONArray groupList = jsonObject1.getJSONArray("group");
		//判断哪些是当前用户所在学校的实义德设备id列表
		MachineEntity machine = new MachineEntity();
		machine.setSchoolCode(schoolCode);
		List<String> currentSchoolMachineIds = machineService.listMachineId(machine);
		List<JSONObject> currentSchoolThdidMachineList = new ArrayList<>();
		//将属于该学校的设备信息挑选出来
		for (int i = 0; i < groupList.size(); i++) {
			JSONObject group = (JSONObject)groupList.get(i);
			JSONArray machineList = group.getJSONArray("children");
			for (int j = 0; j < machineList.size(); j++) {
				JSONObject temp = (JSONObject) machineList.get(j);
				String deviceId = temp.getString("device_id");
				if (currentSchoolMachineIds.contains(deviceId)) {
					JSONObject deviceInfo = new JSONObject();
//				//由于多种设备，所以需要将不同的设备信息转换为统一的字段类表示，设备id为deviceId，设备名为name，在线状态为online，设备sn使用deviceSn
					String name = temp.getString("name");
					boolean online = temp.getBoolean("online");
					String deviceSn = temp.getString("sn");
					deviceInfo.put("deviceId", deviceId);
					deviceInfo.put("name", name);
					deviceInfo.put("online", online);
					deviceInfo.put("deviceSn", deviceSn);
					currentSchoolThdidMachineList.add(deviceInfo);
				}
			}
		}
		List<JSONObject> allTypeMachineList = new ArrayList<>();

		if (currentSchoolThdidMachineList.size() > 0){
			JSONObject thdidMachineList = new JSONObject();
			thdidMachineList.put("name", "人脸识别平板");
			thdidMachineList.put("list", currentSchoolThdidMachineList);
			allTypeMachineList.add(thdidMachineList);
		}
		//获取动态人脸识别设备列表
//		List<JSONObject> currentSchoolDynamicCameraDeviceList = new ArrayList<>();
//		String deviceName = null;
//		String deviceNo = null;
//		com.alibaba.fastjson.JSONArray dynamicCameraDeviceList = DynamicCameraDeviceApi.listDevices(deviceName, deviceNo);
//		for (int i = 0; i < dynamicCameraDeviceList.size(); i++) {
//			com.alibaba.fastjson.JSONObject temp = dynamicCameraDeviceList.getJSONObject(i);
//			String deviceId = temp.getString("deviceId");
//			if (currentSchoolMachineIds.contains(deviceId)){
//				JSONObject deviceInfo = new JSONObject();
////			//由于多种设备，所以需要将不同的设备信息转换为统一的字段类表示，设备id为deviceId，设备名为name，在线状态为online，设备sn使用deviceSn
//				String name = temp.getString("name");
//				String online = temp.getString("onlineStatus");
//				String deviceSn = temp.getString("deviceNo");
//				deviceInfo.put("deviceId", deviceId);
//				deviceInfo.put("name", name);
//				deviceInfo.put("online", online);
//				deviceInfo.put("deviceSn", deviceSn);
//				currentSchoolDynamicCameraDeviceList.add(deviceInfo);
//			}
//		}
//		if (currentSchoolDynamicCameraDeviceList.size() > 0){
//			JSONObject dynamicCameraDevice= new JSONObject();
//			dynamicCameraDevice.put("name", "动态人脸识别摄像头");
//			dynamicCameraDevice.put("list", currentSchoolDynamicCameraDeviceList);
//			allTypeMachineList.add(dynamicCameraDevice);
//		}
		return Msg.success().add("machineList", allTypeMachineList);
	}


	@ApiOperation(value = "获取通行流水记录")
	@GetMapping(value = "/list-passRecord")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "currentPage", paramType = "query", dataType = "Integer", required = true, value = "当前页"),
			@ApiImplicitParam(name = "pageSize", paramType = "query", dataType = "Integer", required = true, value = "每页显示条数"),
			@ApiImplicitParam(name = "schoolCode", paramType = "query", dataType = "Integer", value = "学校id"),
			@ApiImplicitParam(name = "keyword", paramType = "query", dataType = "String", value = "搜索的关键字"),
			@ApiImplicitParam(name = "startTime", paramType = "query", dataType = "Long", value = "开始时间戳"),
			@ApiImplicitParam(name = "endTime", paramType = "query", dataType = "Long", value = "结束时间戳"),
	})
	public JSONObject listPassRecord(Integer currentPage, Integer pageSize, String keyword, Long startTime, Long endTime, Integer schoolCode) {
		JSONObject params = new JSONObject();
		params.put("page", currentPage);
		params.put("amount", pageSize);
		Integer groupId = null;
		//  暂时使用switch代替存储的组名与学校之间的关系
		switch (schoolCode){
			case 510107000:
				groupId = 20;
				break;
            case 510182000:
				groupId = 10;
				break;
            case 510182001:
				groupId = 11;
				break;
            case 510182002:
				groupId = 27;
				break;
            case 510182003:
				groupId = 33;
				break;
            case 510182004:
				groupId = 38;
				break;
            case 510182005:
				groupId = 43;
				break;
		}
		if (groupId != null)
            params.put("personnel_group_id", groupId);
		if (StringUtils.isNoneBlank(keyword))
			params.put("keyword", keyword);
		if (startTime != null)
			params.put("identify_start_time", startTime);
		if (endTime != null)
			params.put("identify_end_time", endTime);
		JSONObject res = thDio.THD_interface("http://62.234.146.219:8088", "/record/list", params, true, "");
		return res;
	}


//	public static void main(String[] args) {
//		List<String> list1 = new ArrayList<String>();
//		for (int i = 0; i < 10000; i++) {
//			list1.add(String.valueOf(i));
//		}
//		List<String> list2 = new ArrayList<>();
//		for (int i = 5000; i < 20000; i++) {
//			list2.add(String.valueOf(i));
//		}
//		long startTime = System.currentTimeMillis();
//		getTheSameSection(list1, list2);
//		System.out.println("操作用时：" + (startTime - System.currentTimeMillis()));
//	}
//
//	public static List getTheSameSection(List<String> list1, List<String> list2) {
//		List<String> resultList = new ArrayList<>();
//		for (String item : list2) {//遍历list2
//			if (list1.contains(item)) {//如果存在这个数
//				resultList.add(item);//放进一个resultList里面，这个resultList就是交集
//			}
////			for (String s : list1) {
////				if (s.equals(item)){
////					resultList.add(item);
////				}
////			}
//		}
//		return resultList;
//	}


//	public static void main(String[] args) {
//		THDio thDio = new THDio();
//		JSONObject params = new JSONObject();
//		params.put("device_id", 105);
//		System.out.println(thDio.THD_interface("/device/info", params, true));
//	}




}
